<template>
  <div>
    <Card>
        <div slot="title" style="display: flex; justify-content: space-between">
          <div style="display: flex">
              <Tabs @on-click="switchTab" type="card">
                  <Tab-pane label="医疗设备" icon="medkit"></Tab-pane>
                  <Tab-pane label="科研设备" icon="ios-medical"></Tab-pane>
                  <Tab-pane label="插座" icon="outlet"></Tab-pane>
              </Tabs>
          </div>
          <div>
              <Tooltip content="新增设备">
                  <Button type="warning" @click="addModal=true" style=" margin-left: 8px"><Icon type="plus"></Icon> </Button>
              </Tooltip>
              <Tooltip content="排序和过滤后的数据">
                  <Button type="primary" @click="exportData(2)"><Icon type="funnel"></Icon> </Button>
              </Tooltip>
              <Tooltip content="原始数据">
                  <Button type="primary" @click="exportData(1)"><Icon type="ios-download"></Icon> </Button>
              </Tooltip>
          </div>
        </div>
        <Table :context="self" :data="tableData" :columns="tableColumns" stripe ref="table" :loading="tableLoading"></Table>
        <div style="margin: 12px; overflow: hidden; font-size: 12px">
            <div style="float: right;">
                <Page :total="tableCount" :current="currentPage" @on-change="changePage" show-total show-elevator></Page>
            </div>
        </div>
    </Card>

    <Modal
      :title="'新增'+typeDict[currentTab]"
      v-model="addModal"
      :mask-closable="false"
      @on-ok="confirmFn('新增')">
      
      <Form :model="addForm" :label-width="120" ref="addV" :rules="addValidate">
        <Form-item label="设备编号" prop="id">
          <Input v-model="addForm.id" placeholder="设备编号/MAC" style="width: 360px" />
        </Form-item>
        <Form-item label="设备类型" prop="category" class="device-add-icon">
          <Select v-model="addForm.category" style="width:330px; vertical-align: top">
            <Option :value="item.id" :label="item.name" :key="item.id" style="width:100%"
                    v-for="item in categoryList">
              <span>{{item.name}}</span>
              <img :src="`https://yxys.io/icons/${item.icon}.png`" width="20px" style="float: right">
            </Option>
          </Select>
          <div style="display: inline-block; padding: 5px; height: 32px;">
            <img :src="!!addForm.category?`https://yxys.io/icons/${categoryId2Key(this.addForm.category,'icon')}.png`:' '" width="20px" />
          </div>
        </Form-item>
        <Form-item label="设备型号" prop="model">
          <Input v-model="addForm.model" placeholder="型号" style="width: 360px" />
        </Form-item>
        <Form-item label="绑定插座" prop="powerStrip">
          <Select v-model="addForm.powerStrip" placeholder="请选择" style="width: 360px">
            <Option :label="item.id" style="width:100%" v-for="item in powerStripList" :value="item" :key="item">
              {{item}}
            </Option>
          </Select>
        </Form-item>
        <Form-item label="所属科室" prop="owner">
          <Select v-model="addForm.owner" style="width:360px; vertical-align: top" filterable>
            <Option :value="item.deptId" :label="item.deptName" :key="item.deptId" style="width:100%"
                    v-for="item in deptList">
              <span>{{item.deptName}}</span>
            </Option>
          </Select>
        </Form-item>
        <Form-item label="使用科室" prop="user">
          <Select v-model="addForm.user" style="width:360px; vertical-align: top" filterable>
            <Option :value="item.deptId" :label="item.deptName" :key="item.deptId" style="width:100%"
                    v-for="item in deptList">
              <span>{{item.deptName}}</span>
            </Option>
          </Select>
        </Form-item>
      </Form>
    </Modal>
    <Modal
      title="编辑现有设备"
      v-model="editModal"
      :mask-closable="false"
      @on-ok="confirmFn('编辑')">
      <Form :model="editForm" :label-width="120" ref="editV" :rules="editValidate">
        <Form-item label="设备编号" prop="id">
          <Input disabled v-model="editForm.id" placeholder="请选择" style="width: 360px" />
        </Form-item>
        <Form-item label="设备类型" prop="category" class="device-add-icon">
          <Select v-model="editForm.category" style="width:330px;vertical-align: top ">
            <Option :value="item.id" :label="item.name" :key="item.id" style="width:100%"
                    v-for="item in categoryList">
              <span>{{item.name}}</span>
              <!-- <img :src="`${$mapServer}/icons/${item.icon}.png`" width="20px" style="float: right"> -->
            </Option>
          </Select>
          <div style="display: inline-block; padding: 5px; height: 32px;">
            <img :src="!!editForm.category?`https://yxys.io/icons/${categoryId2Key(this.editForm.category,'icon')}.png`:' '" width="20px" />
          </div>
        </Form-item>
        <Form-item label="设备型号" prop="model">
          <Input v-model="addForm.model" placeholder="型号" style="width: 360px" />
        </Form-item>
        <Form-item label="设备标签" prop="tags" class="device-tags">
          <Select v-model="editForm.tags" placeholder="请选择" style="width: 360px" multiple>
            <Option :label="item.label" style="width:110px" v-for="item in tagList" :value="item.value" :key="item.value">
              <Tag type="dot" :color="item.color">{{item.label}}</Tag>
            </Option>
          </Select>
        </Form-item>
        <Form-item label="所属科室" prop="owner">
          <Select v-model="editForm.owner" style="width:360px; vertical-align: top" filterable class="device-add-owner">
            <Option :value="item.deptId" :label="item.deptName" :key="item.deptId" style="width:100%"
                    v-for="item in deptList">
              <span>{{item.deptName}}</span>
            </Option>
          </Select>
        </Form-item>
        <Form-item label="使用科室" prop="user">
          <Select v-model="editForm.user" style="width:360px; vertical-align: top" filterable class="device-add-user">
            <Option :value="item.deptId" :label="item.deptName" :key="item.deptId" style="width:100%"
                    v-for="item in deptList">
              <span>{{item.deptName}}</span>
            </Option>
          </Select>
        </Form-item>
      </Form>
    </Modal>
  </div>
</template>

<script>
import { tableColumns } from "./data/device";

export default {
  name: "Device-type",
  async mounted() {
    window.remove = this.remove;
    window.edit = this.edit;
    this.changePage(1);
    // this.tagList = (await this.$getRemoteData(
    //   `${this.$mapServer}/services/config/tag/0/0/1000000000`,
    //   { method: "get" }
    // )).data.tags.map(item => {
    //   return {
    //     label: item.tag_name,
    //     value: item.tag_id
    //     // color: this.colorList[item.color - 1]
    //   };
    // });
    this.categoryList = (await this.$getRemoteData(
      `${this.$mapServer}/equip/services/config/deviceCategory/0/0/9999999`
    )).data.data;
    this.deptList = (await this.$getRemoteData(
      `${this.$mapServer}/equip/services/config/deptList`
    )).data;
    this.powerStripList = (await this.$getRemoteData(
      `${
        this.$mapServer
      }/equip/services/device/deviceFilter?dept=10000&category=30000`
    )).data;
  },
  data() {
    return {
      self: this,
      tableColumns,
      addModal: false,
      editModal: false,
      tableLoading: false,
      colorList: this.$store.state.colorDict,
      confirmText: "",
      editRowIndex: "",
      confirmTextLong: "",
      currentTab: 0,
      currentPage: 1,
      tagList: [],
      deptList: [],
      powerStripList: [],
      deptDict: {},
      categoryList: [],
      categoryNDict: {},
      addValidate: {
        id: [
          {
            type: "string",
            required: true,
            message: "设备编号不能为空",
            trigger: "change"
          }
        ],
        category: [
          {
            type: "string",
            required: true,
            message: "设备类型不能为空",
            trigger: "change"
          }
        ]
      },
      editValidate: {
        category: [
          {
            type: "string",
            required: true,
            message: "设备类型不能为空",
            trigger: "change"
          }
        ],
        code: [{ required: true, message: "设备编号不能为空", trigger: "blur" }]
      },
      typeDict: ["医疗设备", "科研设备", "插座"],
      addForm: {
        id: "",
        category: "",
        model: "",
        owner: "",
        user: "",
        powerStrip: "",
        tags: []
      },
      editForm: {
        category: "",
        model: "",
        owner: "",
        user: "",
        code: "",
        powerStrip: "",
        tags: []
      },
      tableData: [],
      tableCount: 0
    };
  },

  methods: {
    async changePage(pageN) {
      this.currentPage = pageN;
      this.tableLoading = true;
      let tmpTable = await this.$getRemoteData(
        `${this.$mapServer}/equip/services/device/get/${this.currentTab}/${(this
          .currentPage -
          1) *
          10}/10`
      );
      this.tableData = tmpTable.data.data;
      this.tableCount = parseInt(tmpTable.data.count);
      this.tableLoading = false;
    },
    exportData() {
      this.$refs.table.exportCsv({
        filename: ["医疗", "科研"][this.currentTab] + "设备列表",
        original: false,
        columns: this.tableColumns.filter((col, index) => index < 6),
        data: this.tableData.filter((data, index) => {
          return true;
        })
      });
    },
    categoryId2Key(value, field, listField = "id") {
      return this.categoryList.filter(item => {
        return item[listField].toString() === value.toString();
      })[0][field];
    },
    deptId2Key(value, field, listField = "deptId") {
      return this.deptList.filter(item => {
        return item[listField].toString() === value.toString();
      })[0][field];
    },
    switchTab(n) {
      this.currentTab = n;
      this.changePage(1);
    },
    edit(n) {
      this.editRowIndex = n;
      this.editModal = true;
      this.editForm = {
        id: this.tableData[n].id.toString(),
        category: this.categoryId2Key(
          this.tableData[n].categoryName.toString(),
          "id",
          "name"
        ),
        owner: this.deptId2Key(
          this.tableData[n].deptName,
          "deptId",
          "deptName"
        ),
        user: this.deptId2Key(this.tableData[n].userDept, "deptId", "deptName"),
        tags: this.tableData[n].tags
      };
    },
    remove(n) {
      this.editRowIndex = n;
      this.confirmFn("删除");
    },
    confirmFn(text) {
      switch (text) {
        case "新增":
          this.$refs["addV"].validate(valid => {
            if (valid) {
              const category = this.categoryId2Key(
                this.addForm.category,
                "name"
              );
              this.confirmTextLong = `${category}<br/>型号：${
                this.addForm.model ? this.addForm.model : "未知"
              }<br/>${this.addForm.id ? "编号：" + this.addForm.id : ""}`;
              this.$Modal.confirm({
                title: `确认${text}设备`,
                content: `<p>确认${text}设备:<br><span style="font-weight: bold">${
                  this.confirmTextLong
                }</span></p>`,
                loading: true,
                onOk: () => {
                  this.finalConfirmFn(text);
                },
                onCancel: this.cancelFn
              });
            } else {
              this.$Message.error("请注意需要填写的内容!");
              this.$nextTick(() => {
                this.addModal = true;
              });
            }
          });
          break;
        case "编辑":
          this.$refs["editV"].validate(valid => {
            if (valid) {
              this.confirmTextLong = `${
                this.tableData[this.editRowIndex].categoryName
              } 型号：${
                this.editForm.model ? this.editForm.model : "未知 "
              }（编号: ${this.tableData[this.editRowIndex].id}）`;
              this.$Modal.confirm({
                title: `确认${text}设备`,
                content: `<p>确认${text}设备:<br><span style="font-weight: bold">${
                  this.confirmTextLong
                }</span> ？</p>`,
                loading: true,
                onOk: () => {
                  this.finalConfirmFn(text);
                },
                onCancel: this.cancelFn
              });
            } else {
              this.$Message.error("请注意需要填写的内容!");
              this.$nextTick(() => {
                this.editModal = true;
              });
            }
          });
          break;
        case "删除":
          this.confirmTextLong = `${
            this.tableData[this.editRowIndex].categoryName
          }（ID: ${this.tableData[this.editRowIndex].id}）`;
          this.$Modal.confirm({
            title: `确认${text}设备`,
            content: `<p>确认${text}设备:<br><span style="font-weight: bold">${
              this.confirmTextLong
            }</span> </p>`,
            loading: true,
            onOk: () => {
              this.finalConfirmFn(text);
            },
            onCancel: this.cancelFn
          });
          break;
      }
    },
    cancelFn() {
      this.$Modal.remove();
      switch (this.confirmText) {
        case "新增":
          this.addModal = true;
          break;
        case "编辑":
          this.editModal = true;
          break;
        case "删除":
          break;
      }
    },
    async finalConfirmFn(action) {
      let result;
      try {
        switch (action) {
          case "新增":
            let tmpAdd = {
              deviceId: this.addForm.id,
              coulometerId: this.addForm.powerStrip,
              name: this.addForm.model,
              category: this.addForm.category,
              tag: JSON.stringify(this.addForm.tags),
              floor_id: "",
              building_id: "",
              campus_id: 0,
              x: "",
              y: "",
              user_dept_id: this.addForm.user,
              owner_depit_id: this.addForm.owner
            };
            result = await this.$getRemoteData(
              `${this.$mapServer}/equip/services/device/add/`,
              {
                method: "POST",
                data: tmpAdd
              }
            );
            if (result.data.response_code == "000000") {
              this.$Message.success("新增设备成功");
              this.changePage(this.currentPage);
            } else {
              this.$Message.error("新增设备出错，请检查网络情况");
            }
            this.$Modal.remove();
            break;
          case "编辑":
            let tmpEdit = {
              deviceId: this.editForm.id,
              category: this.editForm.category,
              tag: JSON.stringify([]),
              floor_id: "",
              building_id: "",
              campus_id: 0,
              x: "",
              y: "",
              user_dept_id: this.editForm.user,
              owner_depit_id: this.editForm.owner
            };
            result = await this.$getRemoteData(
              `${this.$mapServer}/equip/services/device/update`,
              {
                method: "PUT",
                data: tmpEdit
              }
            );
            if (result.data.response_code == "000000") {
              this.$Message.success("编辑设备成功");
              this.changePage(this.currentPage);
            } else {
              this.$Message.error("编辑设备出错，请检查网络情况");
            }
            this.$Modal.remove();
            break;
          case "删除":
            result = await this.$getRemoteData(
              `${this.$mapServer}/equip/services/device/delete?deviceId=${
                this.tableData[this.editRowIndex].id
              }`,
              {
                method: "DELETE"
              }
            );
            if (result.data.response_code == "000000") {
              this.$Message.success("删除设备成功");
              this.changePage(this.currentPage);
            } else {
              this.$Message.error("删除设备出错，请检查网络情况");
            }
            this.$Modal.remove();
            break;
        }
      } catch (e) {
        console.error(e);
        this.$Message.error(`${this.confirmText}设备出错，请检查网络情况`);
        this.$Modal.remove();
      }
    }
  }
};
</script>


<style>
.device-add-owner .ivu-select-dropdown,
.device-add-user .ivu-select-dropdown {
  top: auto !important;
  left: auto !important;
}

.ivu-table-tbody .ivu-tooltip-rel,
.ivu-table-tbody .ivu-tooltip {
  width: 100%;
}

.ivu-table-tbody .ivu-tooltip-popper .ivu-tooltip-inner {
  white-space: normal !important;
}

.ivu-table table {
  overflow-x: hidden;
}

textarea.ivu-input {
  font-size: 12px !important;
  padding-top: 6px;
  padding-bottom: 6px;
}

.device-icon .ivu-select-dropdown {
  padding: 5px 12px !important;
}

.device-icon .ivu-select-item-selected,
.ivu-select-item-selected:hover {
  background: #eee !important;
}

.device-icon .ivu-form-item-content {
  display: flex;
  justify-content: space-between;
}

.device-icon .ivu-select-item span {
  width: 32px;
  transform: translateX(16px);
  text-align: center;
}

.search-input input {
  padding: 0 !important;
  height: 22px;
  border: 0;
}

.search-input input:focus {
  box-shadow: none;
}

.search-input::after {
  content: "";
  border-bottom: 1px solid #aaa;
  width: 0;
  margin-left: 45px;
  display: block;
  transition: all 0.5s;
}

.search-input.focused::after {
  transition: all 0.5s;
  margin-left: 0;
  width: 90px;
}

.search-select .ivu-select-selection {
  border: 0;
  box-shadow: none !important;
  background: transparent;
}

.search-select:focus {
  box-shadow: none;
  outline: 0;
}

.device-add-icon .ivu-form-item-content {
  height: 33px;
}
</style>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.search-select {
  width: 80px;
  position: absolute;
  top: 46px;
  right: 200px;
}

.search-input {
  position: absolute;
  top: 50px;
  right: 96px;
  width: 90px;
}

.device-tags .ivu-select-item {
  padding: 7px 5px;
}

.tab-search-icon {
  right: 104px;
  transition: right 0.3s;
}

.tab-export-icon {
  right: 24px;
}

.tab-add-icon {
  right: 64px;
}

h1,
h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  /*margin: 0 10px;*/
}

a {
  color: #42b983;
}
</style>
